package com.example.springboottest.example.clickhouse;

import com.github.housepower.jdbc.ClickHouseConnection;

import java.sql.*;

public class ClickHouseTest {
    public static void main(String[] args) {
        writeData();
//        readData();
    }

    public static void readData() {
        Connection connection = null;
        try {
            Class.forName("com.github.housepower.jdbc.ClickHouseDriver");
            connection = DriverManager.getConnection("jdbc:clickhouse://localhost:9000");

            Statement statement = connection.createStatement();

            String sql = "select * from default.stu";
            ResultSet rs = statement.executeQuery(sql);

            while (rs.next()) {
                // ResultSet 的下标值从 1 开始，不可使用 0，否则越界，报 ArrayIndexOutOfBoundsException 异常
                System.out.println(rs.getInt(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void writeData() {
        Connection connection = null;
        try {
            System.setProperty("illegal-access", "allow");

            String insertQuery = "INSERT INTO default.stu(id, name, address) VALUES(?, ?, ?)";

            Class.forName("com.github.housepower.jdbc.ClickHouseDriver");
            connection = DriverManager.getConnection("jdbc:clickhouse://127.0.0.1:9000");



            PreparedStatement pstmt = connection.prepareStatement(insertQuery);
            pstmt.setInt(1, new Integer(3));
            pstmt.setString(2, "test");
            pstmt.setString(3, "test");

            pstmt.addBatch();
            pstmt.executeBatch();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

//    public void connect() {
//        ClickHouseConnection conn = null;
//
//        ClickHouseProperties properties = new ClickHouseProperties();
//
//        properties.setUser("hmt");
//
//        properties.setPassword("Wbvc6G7f");
//
//        properties.setDatabase("huang");
//
//        try {
//
//
//            ClickHouseDataSource dataSource = new ClickHouseDataSource("jdbc:clickhouse://192.168.25.130:8123", properties); //default表示数据表 ,port原来为8123
//
//            ClickHouseConnectionImpl connection = (ClickHouseConnectionImpl) dataSource.getConnection();
//
//            if (connection != null) {
//                System.out.println("连接成功");
//
//            }
//        } catch (SQLException e) {
//// TODO Auto-generated catch block
//
//            e.printStackTrace();
//
//        }
//
//    }
}
